package com.taiyuan.tongcheng.ui.fragment;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;
import org.kymjs.kjframe.utils.StringUtils;

import com.alibaba.fastjson.JSON;
import com.taiyuan.tongcheng.adapter.MovingOrderAdapter;
import com.taiyuan.tongcheng.adapter.MovingOrderAdapter;
import com.taiyuan.tongcheng.application.TCBroadcastAction;
import com.taiyuan.tongcheng.bean.BjOrderInfo;
import com.taiyuan.tongcheng.bean.PageInfo;
import com.taiyuan.tongcheng.bean.BjOrderInfo;
import com.taiyuan.tongcheng.bean.ZcOrderInfo;
import com.taiyuan.tongcheng.http.HttpParamUtil;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.ui.LoginActivity;
import com.taiyuan.tongcheng.ui.MovingOrderDetailActivity;
import com.taiyuan.tongcheng.ui.OrderDetailActivity;
import com.taiyuan.tongcheng.util.DialogUtil;
import com.taiyuan.tongcheng.widget.EmptyLayout;
import com.taiyuan.tongcheng.widget.listview.FooterLoadingLayout;
import com.taiyuan.tongcheng.widget.listview.PullToRefreshBase;
import com.taiyuan.tongcheng.widget.listview.PullToRefreshList;
import com.taiyuan.tongcheng.widget.listview.PullToRefreshBase.OnRefreshListener;
import com.tytc56.user.R;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
/**
 * 
* @Description 搬家订单
* @author Administrator  
* @date 2015-8-29 下午10:23:10 
* @update (date)
* @version V1.0
 */
public class OrderMovingFragment extends KJFragment{
	
    @BindView(id = R.id.empty_layout)
    private EmptyLayout mEmptyLayout;
    @BindView(id = R.id.pull_list_moving)
    private PullToRefreshList mRefreshLayout;
    private ListView mList;
    
    //http工具
    private KJHttp  kjHttp;
    private final String GET_CARGO_DATA = TcWebservice.WEBSERVER_IP+TcWebservice.API.MOVING_ORDER_GET_LIST;
    private String orderListcache; //订单缓存集合
    private HttpParams  httpParame;
    
    //page页信息
    private PageInfo pageInfo =new PageInfo();
    private int tcPage=0;
    private List<BjOrderInfo> OrderList = new ArrayList<BjOrderInfo>();
    private List<String > cargonStringList =new ArrayList<String>();
    //适配器
    private MovingOrderAdapter  orderAdapter;
    private Intent detailIntent;
    private IntentFilter  intentFilter;
    public static final  String TAG_MOVING_ORDER="TAG_MOVING_ORDER" ;
    //进度条显示
    private Dialog  tcLoaddingDialog;
	@SuppressLint("NewApi")
	@Override
	protected View inflaterView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
		 return View.inflate(getActivity(), R.layout.fragment_moving, null);
	}
   
	@SuppressLint("NewApi")
	@Override
	protected void initWidget(View parentView) {
		super.initWidget(parentView);
		detailIntent=new Intent(getActivity(),MovingOrderDetailActivity.class);
		tcLoaddingDialog=DialogUtil.getTcLoadding(getActivity());
		//注册广播监听
		registReceiver();
		listViewPreference();
    	orderAdapter=new MovingOrderAdapter(getActivity(), OrderList);
        mList.setAdapter(orderAdapter);
    	mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                refresh();
            }
        });
    	fillOrderData();
	}
	
	/**
	 * 
	* @Description: 广播刷新订单状态
	* @return void
	* @throws 
	* @autour wzq
	* @date 2015-9-14 下午4:16:59
	* @update (date)
	 */
	@SuppressLint("NewApi") private void registReceiver() {
		intentFilter =new IntentFilter();
		intentFilter.addAction(TCBroadcastAction.SUCCESS_CANCEL_CARGO);
		intentFilter.addAction(TCBroadcastAction.SUCCESS_WX_PAY_OK);
		intentFilter.addAction(TCBroadcastAction.ERROR_WX_PAY_CANCEL);
		intentFilter.addAction(TCBroadcastAction.DIALOG_SHOW);
		intentFilter.addAction(TCBroadcastAction.SUC_MOVING_ORDER);
		intentFilter.addAction(TCBroadcastAction.ERROR_MOVING_ORDER);
		intentFilter.addAction(TCBroadcastAction.SUC_CONFIRM_MODIFY);
		intentFilter.addAction(TCBroadcastAction.ERROR_CONFIRM_MODIFY);
		getActivity().registerReceiver(receiver, intentFilter);
	}
	
	
	private BroadcastReceiver  receiver =new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if(TCBroadcastAction.SUCCESS_CANCEL_CARGO.equals(intent.getAction())){
				fillOrderData();
			}
			if(TCBroadcastAction.SUCCESS_WX_PAY_OK.equals(intent.getAction())){
				fillOrderData();
				if(tcLoaddingDialog!=null&&tcLoaddingDialog.isShowing()){
					tcLoaddingDialog.cancel();
				}
				ViewInject.toast("订单支付成功");
			}
			if(TCBroadcastAction.ERROR_WX_PAY_CANCEL.equals(intent.getAction())){
				if(tcLoaddingDialog!=null&&tcLoaddingDialog.isShowing()){
					tcLoaddingDialog.cancel();
				}
				ViewInject.toast("订单支付失败");
			}
			if(TCBroadcastAction.DIALOG_SHOW.equals(intent.getAction())){
				tcLoaddingDialog.show();
			}
			
			if(TCBroadcastAction.ERROR_MOVING_ORDER.equals(intent.getAction())){
				if(tcLoaddingDialog!=null&&tcLoaddingDialog.isShowing()){
					tcLoaddingDialog.cancel();
				}
			}
			if(TCBroadcastAction.SUC_MOVING_ORDER.equals(intent.getAction())){
				fillOrderData();
				if(tcLoaddingDialog!=null&&tcLoaddingDialog.isShowing()){
					tcLoaddingDialog.cancel();
				}
			}
			if(TCBroadcastAction.ERROR_CONFIRM_MODIFY.equals(intent.getAction())){
				if(tcLoaddingDialog!=null&&tcLoaddingDialog.isShowing()){
					tcLoaddingDialog.cancel();
				}
			}
			if(TCBroadcastAction.SUC_CONFIRM_MODIFY.equals(intent.getAction())){
				fillOrderData();
				if(tcLoaddingDialog!=null&&tcLoaddingDialog.isShowing()){
					tcLoaddingDialog.cancel();
				}
			}
		}
	};
	
	/**
	  * 
	 * @Description: 初始话样式
	 * @return void
	 * @throws
	 * @autour Administrator
	 * @date 2015-8-30 下午12:37:39 
	 * @update (date)
	  */
    @SuppressLint("NewApi")
	private void listViewPreference() {
        mList = mRefreshLayout.getRefreshView();
        mList.setDivider(new ColorDrawable(android.R.color.transparent));
        mList.setOverscrollFooter(null);
        mList.setOverscrollHeader(null);
        mList.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        mRefreshLayout.setPullLoadEnabled(true);
        ((FooterLoadingLayout) mRefreshLayout.getFooterLoadingLayout())
                .setNoMoreDataText("没有更多的数据了");

        mList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            	
            	//列表点击方法
            	Bundle bundle =new Bundle();
            	bundle.putSerializable(TAG_MOVING_ORDER,OrderList.get(position) );
            	detailIntent.putExtras(bundle);
            	startActivity(detailIntent);
            }
        });

        
        
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener<ListView>() {
            
        	@Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            	fillOrderData();
            }

            
            @Override
            public void onPullUpToRefresh(
                PullToRefreshBase<ListView> refreshView) {
                refresh();
            }
        });
    }
	
	
    private void fillOrderData() {
    	tcPage=1;
    	getCargoOrderList(1);
    }

    private void refresh() {
    	getCargoOrderList(tcPage);
    }
   
    /**
     * 获取订单信息列表
     * @param 
     */
    @SuppressLint("NewApi")
	private void getCargoOrderList(final int page) {

		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjh = new KJHttp(config);
		HttpParams params = new HttpParams();
        params= HttpParamUtil.getMovingListParams(getActivity(), 10, page, "desc");
        kjh.post(TcWebservice.WEBSERVER_IP+TcWebservice.API.MOVING_ORDER_GET_LIST, params, new HttpCallBack() {

			@Override
			public void onSuccess(String t) {
				super.onSuccess(t);
				String str;
				try {
					str = URLDecoder.decode(new String(t), "UTF-8");
					KJLoger.debug(str);
					WebData webData = TcJsParser.getWedataData(str);
					if (webData.getStatus() == 1) {
						com.alibaba.fastjson.JSONObject cargoListJson =JSON.parseObject(webData.getData());  
						List<BjOrderInfo > cargoOrderList=new ArrayList<BjOrderInfo>();
						cargoOrderList.clear();
						pageInfo = JSON.parseObject( cargoListJson.getString("pageInfo"), PageInfo.class);
						KJLoger.debug(pageInfo.toString());
						//解析搬家订单
						cargonStringList=JSON.parseArray(cargoListJson.getString("dataList"), String.class);
						for (String jsonString : cargonStringList) {
							BjOrderInfo info = JSON.parseObject(jsonString,BjOrderInfo.class);
							cargoOrderList.add(info);
						}
						if(page==1){
						   OrderList.clear();
						   OrderList.addAll(cargoOrderList);
						}else{
						   OrderList.addAll(cargoOrderList);
						}
						  tcPage++;
						  KJLoger.debug("list-size="+cargoOrderList.size()+"=tcpage="+tcPage);
						orderAdapter.notifyDataSetChanged();
						 mEmptyLayout.dismiss();
						KJLoger.debug(OrderList.toString());
					}else if(webData.getStatus()==-1){
						
						ViewInject.toast(webData.getMsg());
						startActivity(new Intent(getActivity(),LoginActivity.class));
					}else {
						mEmptyLayout.setErrorType(EmptyLayout.NODATA);
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			
			@Override
    		public void onFailure(int errorNo, String strMsg) {
    			super.onFailure(errorNo, strMsg);
    			//样例数据
    			BaseAdapter  sampAdapter = null ;
    			//获取失败
				if (sampAdapter != null && sampAdapter.getCount() > 0) {
					return;
				} else {
					mEmptyLayout.setErrorType(EmptyLayout.NODATA);
				}
    		}
    		
    		
    		@Override
    		public void onFinish() {
    			super.onFinish();
    			//关闭上拉、下拉刷写
    	         mRefreshLayout.onPullDownRefreshComplete();
                 mRefreshLayout.onPullUpRefreshComplete();
    		}
        });
         
	}
    
    @SuppressLint("NewApi") @Override
    public void onDestroyView() {
    	super.onDestroyView();
    	getActivity().unregisterReceiver(receiver);
    }
	
}
